package com.yupi.yupao.controller;

import com.yupi.yupao.common.BaseResponse;
import com.yupi.yupao.common.ErrorCode;
import com.yupi.yupao.common.ResultUtils;
import com.yupi.yupao.exception.BusinessException;
import com.yupi.yupao.model.domain.Message;
import com.yupi.yupao.model.domain.TeamMessage;
import com.yupi.yupao.model.domain.User;
import com.yupi.yupao.model.domain.request.MessageAddRequest;
import com.yupi.yupao.model.domain.request.TeamMessageAddRequest;
import com.yupi.yupao.service.MessageService;
import com.yupi.yupao.service.TeamMessageService;
import com.yupi.yupao.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/teamMessage")
@CrossOrigin(origins = {"https://www.dynamic-qhe.com.cn","http://localhost"},allowCredentials = "true")
@Slf4j
public class TeamMessageController {

    @Resource
    private TeamMessageService teamMessageService;

    @Resource
    private UserService userService;

    /**
     * 发送信息
     * @param teamMessageAddRequest
     * @param request
     * @return
     */


    @PostMapping("/add")
    public BaseResponse<Boolean> addMessage(@RequestBody TeamMessageAddRequest teamMessageAddRequest, HttpServletRequest request){
        if (teamMessageAddRequest == null){
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }

        User loginUser = userService.getLoginUser(request);

        TeamMessage teamMessage = new TeamMessage();

        teamMessage.setFrom_id(loginUser.getId());
        teamMessage.setFrom_userName(loginUser.getUsername());
        teamMessage.setCreate_time(new Date());
        // 这个函数，是吧前面的字段的值，赋值给后面的字段
        BeanUtils.copyProperties(teamMessageAddRequest,teamMessage);


        boolean result = teamMessageService.insertMessage(teamMessage);

        return ResultUtils.success(result);

    }

    /**
     * 根据队伍id查询 一个队伍中所有的message
     * @param teamId
     * @return
     */
    @GetMapping("/get")
    public BaseResponse<List<TeamMessage>> getMessageById(long teamId){
        //判空数据
        if(teamId < 0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }


        List<TeamMessage> list = teamMessageService.getMessageByTid(teamId);

        if (list == null){
            return ResultUtils.success(null);
        }

        return ResultUtils.success(list);
    }


}
